# -*- coding: utf-8 -*-
"""
openworship - Open Source Church Service Management
Copyright (c) 2008 Kevin Landers

Portions copyright (c) 2008 Raoul Snyman, Joshua Biagio, Michael Lucas and
Scott Guerrieri

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.

This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
"""

"""
The base Controller API
Provides the BaseController class for subclassing.
"""
import logging

from decorator import decorator

from paste.request import construct_url
from paste.httpexceptions import HTTPMovedPermanently

from pylons import tmpl_context as c, request, session
from pylons.controllers import WSGIController
from pylons.templating import render_mako as render

from openworship.lib import helpers as h
from openworship.model.meta import Session
from openworship.model import Member

class BaseController(WSGIController):
    public_urls = ['/member/login/', '/member/logout/']

    def __before__(self):
        """
        Check if the user needs to be logged in, and if they are logged in.
        """
        if not 'REMOTE_USER' in session:
            if not request.environ['PATH_INFO'] in self.public_urls:
                session['path_before_login'] = request.environ['PATH_INFO']
                session.save()
                h.redirect_to(h.url_for('/member/login/'))

    def __call__(self, environ, start_response):
        """
        Invoke the Controller

        WSGIController.__call__ dispatches to the Controller method
        the request is routed to. This routing information is
        available in environ['pylons.routes_dict']
        """
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()


def check_access(permission):
    """
    A decorator used to check the access level of a member against a permission.
    """
    def validate(func, self, *args, **kwargs):
        if 'REMOTE_USER' in session:
            member = Session.query(Member).get(session['REMOTE_USER'])
            if member.has_access(permission):
                return func(self, *args, **kwargs)
            else:
                h.flash.set_message('You don\'t have access to that area.', 'error')
                h.redirect_to('/')
        else:
            return func(self, *args, **kwargs)
    return decorator(validate)
